package com.hongkuncheng.cms.controller.admin;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.LockMode;
import org.hibernate.sql.JoinType;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.model.Admin;
import com.hongkuncheng.cms.model.Checkflow;
import com.hongkuncheng.cms.model.Checknode;
import com.hongkuncheng.cms.model.ChecknodeReAdmin;
import com.hongkuncheng.cms.model.ChecknodeType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 审核流程管理
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/checkflow")
public class AcheckflowController extends BaseController {

    // 流程列表
    @RequestMapping
    public String index() {
        List<Checkflow> checkflows = factorySession.createCriteria(Checkflow.class).list();
        request.setAttribute("checkflows", checkflows);
        return view();
    }

    // 流程编辑
    @RequestMapping("edit")
    public String edit() {
        int checkflowId = request.getParameter("checkflowid") == null ? 0 :
                Integer.parseInt(request.getParameter("checkflowid"));
        Checkflow checkflow = checkflowId == 0 ? new Checkflow() : factorySession.get(Checkflow.class, checkflowId);
        request.setAttribute("checkflow", checkflow);
        return view();
    }

    // 流程编辑处理
    @RequestMapping("editdo")
    @ResponseBody
    public void editdo() {
        checkAdminPermission("yunwei_systemsetup_checkflow");
        int checkflowId = Integer.parseInt(request.getParameter("checkflowid"));
        String name = request.getParameter("name");
        int exist = Integer.parseInt(factorySession.createCriteria(Checkflow.class)
                .add(Restrictions.eq("name", name))
                .add(Restrictions.ne("id", checkflowId))
                .setProjection(Projections.count("id")).uniqueResult().toString());
        if (exist > 0) {
            PageHelper.alertAndGoBack("审核流程名称已存在，请重新输入");
            return;
        }
        Checkflow checkflow = checkflowId == 0 ? new Checkflow() :
                factorySession.load(Checkflow.class, checkflowId, LockMode.PESSIMISTIC_WRITE);
        checkflow.setName(name);
        if (checkflowId == 0) {
            factorySession.save(checkflow);
            // 初始化拟稿流程节点
            Checknode checknode = new Checknode();
            checknode.setChecknodeType(factorySession.load(ChecknodeType.class, 1));
            checknode.setCheckflow(checkflow);
            checknode.setName("拟稿");
            checknode.setSingleaudit(false);
            checknode.setCanedit(false);
            checknode.setGroupbydepart(false);
            checknode.setSort(1);
        }
        if (checkflowId == 0) factorySession.save(checkflow);
        recordLog((checkflowId == 0 ? "新建" : "更新") + "审核流程《" + checkflow.getName().trim() + "》");
        PageHelper.alertAndRedirect("保存成功", "./");
    }

    // 流程删除
    @RequestMapping("delete")
    @ResponseBody
    public void delete() {
        checkAdminPermission("yunwei_systemsetup_checkflow");
        int checkflowId = Integer.parseInt(request.getParameter("checkflowid"));
        Checkflow checkflow = factorySession.load(Checkflow.class, checkflowId, LockMode.PESSIMISTIC_WRITE);
        factorySession.delete(checkflow);
        PageHelper.alertAndRedirect("删除成功", "./");
        recordLog("删除审核流程《" + checkflow.getName().trim() + "》");
    }

    // 是否启用
    @RequestMapping("isactive")
    @ResponseBody
    public void isactive() throws Exception {
        checkAdminPermission("yunwei_systemsetup_checkflow");
        int checkflowId = Integer.parseInt(request.getParameter("checkflowid"));
        Checkflow checkflow = factorySession.load(Checkflow.class, checkflowId, LockMode.PESSIMISTIC_WRITE);
        if (!checkflow.isActive() && checkflow.getChecknodes().size() < 2) {
            PageHelper.alertAndGoBack("启用失败\\n因为该流程缺少有效的审核子节点");
            recordLog("启用审核流程《" + checkflow.getName().trim() + "》，启用失败，因为该流程缺少有效的审核子节点");
        } else {
            checkflow.setActive(!checkflow.isActive());
            String domsg = checkflow.isActive() ? "启用" : "停用";
            recordLog(domsg + "审核流程《" + checkflow.getName().trim() + "》，" + domsg + "成功");
            response.sendRedirect("./");
        }
    }

    // 检测当前用户是否参与审核流程（供Ajax调用）
    @RequestMapping("havecheckflow")
    @ResponseBody
    public void havecheckflow() {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if (admin == null) {
            print(-1);
        } else {
            List<ChecknodeReAdmin> cras = factorySession.createCriteria(ChecknodeReAdmin.class)
                    .createAlias("checknode", "checknode", JoinType.LEFT_OUTER_JOIN)
                    .add(Restrictions.eq("checknode.checknodeType.id", 1))
                    .add(Restrictions.eq("admin.id", admin.getId())).list();
            List<Integer> checkflowIds = new ArrayList<Integer>();
            for (ChecknodeReAdmin cra : cras)
                if (cra.getChecknode().getCheckflow().isActive() &&
                        !checkflowIds.contains(cra.getChecknode().getCheckflow().getId()))
                    checkflowIds.add(cra.getChecknode().getCheckflow().getId());
            print(checkflowIds.size()); // 大于0：有参与的审核流程，等于0：无参与的审核流程
        }
    }

}
